package cn.rkylin.oms.authorization.service;

import cn.rkylin.apollo.common.util.HttpUtil;
import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.utils.HttpRespons;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.net.www.http.HttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.parseObject;

@Service("authorizationService")
public class AuthorizationService {

    /**
     * 店铺服务层
     */
    @Autowired
    private IShopService shopService;

    @Value("${authorization.callback.url}")
    private String callbackUrl;

    @Autowired
    LogUtil logUtil;

    public Map<String, Object> authorizationSuning(String shopId, String code) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();

        if (StringUtils.isEmpty(shopId)) {
            returnMap.put("success", "false");
            returnMap.put("msg", "shopId is null");
            return returnMap;
        }
        ShopVO shopVO = shopService.getShopById(shopId);
        if (shopVO == null) {
            returnMap.put("success", "false");
            returnMap.put("msg", "shopVO is null");
            return returnMap;
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://open.suning.com/api/oauth/token");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type", "authorization_code"));
        // appkey
        params.add(new BasicNameValuePair("client_id", shopVO.getAppKey()));
        // appsecret
        params.add(new BasicNameValuePair("client_secret", shopVO.getAppSecret()));
        // callbackurl
        params.add(new BasicNameValuePair("redirect_uri", callbackUrl));
        // code
        params.add(new BasicNameValuePair("code", code));

        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        StringBuilder respStr = new StringBuilder();
        if (entity != null) {
            InputStream ins = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
            String readData = null;
            while ((readData = br.readLine()) != null) {
                respStr.append(readData);
            }
            if (ins != null) {
                ins.close();
            }
        }

        String resJson = respStr.toString();
        logUtil.info(new DBLog(code, JSON.toJSONString(params), "authorizationSuning", resJson));

        Map<String, Object> jsonMap = parseObject(resJson, Map.class);
        if (jsonMap.containsKey("access_token")) {
            ShopVO shopVOUpdate = new ShopVO();
            shopVOUpdate.setShopId(shopVO.getShopId());
            String access_token = jsonMap.get("access_token").toString();
            shopVOUpdate.setSessionKey(access_token);
            if(jsonMap.containsKey("refresh_token")){
                String refresh_token = jsonMap.get("refresh_token").toString();
                shopVOUpdate.setRefreshToken(refresh_token);
            }
            shopService.update(shopVOUpdate);

            returnMap.put("success", "true");
            returnMap.put("msg", "authorization success");
            return returnMap;
        } else {
            returnMap.put("success", "false");
            returnMap.put("msg", "access_token is null");
            return returnMap;
        }
    }


    /**
     * 唯品会直发授权
     *
     * @param shopId
     * @param code
     * @return
     */
    public Map<String, Object> authorizationVip(String shopId, String code) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();

        if (StringUtils.isEmpty(shopId)) {
            returnMap.put("success", "false");
            returnMap.put("msg", "shopId is null");
            return returnMap;
        }
        ShopVO shopVO = shopService.getShopById(shopId);
        if (shopVO == null) {
            returnMap.put("success", "false");
            returnMap.put("msg", "shopVO is null");
            return returnMap;
        }

        String requestUrl = "https://auth.vip.com/oauth2/token?client_id=" + shopVO.getAppKey() +
                "&client_secret=" + shopVO.getAppSecret() +
                "&grant_type=authorization_code" +
                "&redirect_uri=http://oms.ruixuesoft.com" +
                "&request_client_ip=127.0.0.1" +
                "&code=" + code;

        String resJson = HttpUtils.sendByPost(requestUrl, "");
        Map<String, Object> jsonMap = parseObject(resJson, Map.class);
        if (jsonMap.containsKey("access_token")) {
            String token = jsonMap.get("access_token").toString();
            ShopVO shopVOUpdate = new ShopVO();
            shopVOUpdate.setShopId(shopVO.getShopId());
            shopVOUpdate.setRefreshToken(token);
            shopService.update(shopVOUpdate);
            returnMap.put("success", "true");
            returnMap.put("msg", "authorization success");

        } else {
            returnMap.put("success", "false");
            returnMap.put("msg", "access_token is null");
        }
        return returnMap;
    }

    /**
     * 获取授权地址
     *
     * @param shopId
     * @return
     */
    public Map<String, Object> getAuthorizationUrl(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();

        if (StringUtils.isEmpty(shopId)) {
            returnMap.put("success", "false");
            returnMap.put("msg", "shopId is null");
            return returnMap;
        }
        ShopVO shopVO = shopService.getShopById(shopId);
        if (shopVO == null) {
            returnMap.put("success", "false");
            returnMap.put("msg", "shopVO is null");
            return returnMap;
        }

        String returnUrl = "";
        if (shopVO.getShopType().equals("唯品会直发")) {
            returnUrl = "https://auth.vip.com/oauth2/authorize?client_id=" + shopVO.getAppKey() + "&response_type=code&" +
                    "redirect_uri=" + callbackUrl + "/authorization/authorizationVip/shopId/" + shopVO.getShopId() + ".action";
            returnMap.put("success", "true");
            returnMap.put("msg", returnUrl);
        } else if (shopVO.getShopType().equals("苏宁")) {
            returnUrl = "https://open.suning.com/api/oauth/authorize?response_type=code&client_id=" + shopVO.getAppKey() + "&" +
                    "redirect_uri=" + callbackUrl + "/authorization/authorizationSuning/shopId/" + shopVO.getShopId() + ".action" +
                    "&scope=item,price,catagory,order&state=1231414&itemcode=ruixueERP";
            returnMap.put("success", "true");
            returnMap.put("msg", returnUrl);
        } else {
            returnMap.put("success", "false");
            returnMap.put("msg", "");
        }
        return returnMap;
    }


}
